//
let baseURL = ''
const request = {
  invoke(args) {
    const loginInfo = uni.getStorageSync('loginInfo');
    let cookies = '';
    if (loginInfo && loginInfo.cookie_info) {
      // cookies = loginInfo.cookie_info.cookies.map(cookie => {
      //   return `${cookie.name}=${cookie.value}`;
      // }).join(';');
      cookies = loginInfo.cookie_info.cookies
    }
    // 确保 headers 对象已定义
    args.header = {
      "content-type": "application/x-www-form-urlencoded"
    };



    const token = uni.getStorageSync('token')
    // 如果存在 token，则添加到请求头
    // if (token) {
    //   args.header.Authorization = `Bearer ${token}`;
    // }
    // console.log('cookies', cookies);
    if (cookies) {
      args.cookies = cookies;
    }
    console.log('args', args);
  },
  success(e) {

  },
  complete(res) {

  },
  fail(e) {
    console.log('fail', e);

    if (e.errMsg.includes('statusCode:-1')) {
      return uni.showToast({
        title: '网络请求超时',
        duration: 3000,
        icon: "none"
      })
    }
    uni.showToast({
      title: '网络错误',
      duration: 3000,
      icon: "none"
    })
  }
};

uni.addInterceptor("request", request);
uni.addInterceptor("uploadFile", request);

export default (options) => {
  if (options.hasOwnProperty('showLoading') && options.showLoading) {
    uni.showLoading({
      title: "加载中",
      icon: 'none',
      mask: true
    });
  }
  return new Promise((resolve, reject) => {
    uni.request({
      withCredentials: true,
      ...options,
      success(res) {
        console.log('request', res);
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (res.data.code == 1011008 || res.data.code == 1011004 || res.data.code == 1011009 || res.data.code == 1011006) {
            uni.clearStorageSync();
            uni.reLaunch({
              url: '/pages/login/index'
            })
          } else {
            resolve(res.data);
          }

        } else {
          if (res.statusCode === 401) {
            uni.reLaunch({
              url: '/pages/login/index'
            })
          }
          resolve(res.data);
        }

      },
      fail(err) {
        console.log('err', err);
        reject(err);
      },
      complete() {
        if (options.hasOwnProperty('showLoading') && options.showLoading) {
          uni.hideLoading()
        }
      }
    });
  });
};